import Axios from 'axios'
import baseURL from '_conf/url'
import { Message } from 'iview'
import Cookies from 'js-cookie'
import { TOKEN_KEY } from '@/libs/util'
import {refreshToken} from '@/api/user'
import { setToken,sessionRead,sessionSave,getToken } from './util'
import Vue from 'vue'
window.isReresh = false;

import { toggleHeadingBigger } from 'simplemde'
class httpRequest {
  constructor () {
    this.options = {
      method: '',
      url: ''
    }
    // 存储请求队列
    this.queue = {}
  }
  // 销毁请求实例
  destroy (url) {
    delete this.queue[url]
    const queue = Object.keys(this.queue)
    return queue.length
  }
  // 请求拦截
  interceptors (instance, url) {
    // 添加请求拦截器
    instance.interceptors.request.use(config => {
      if (!config.url.includes('/users')) {
        config.headers['Authorization'] = getToken()
      }
      // Spin.show()
      // 在发送请求之前做些什么
      return config
    }, error => {
      // 对请求错误做些什么
      return Promise.reject(error)
    })

    // 添加响应拦截器
    instance.interceptors.response.use((res) => {
      let { data } = res
      const is = this.destroy(url)
      let expire=sessionRead("timeout")
      if (expire) {
        let dateEnd = new Date(expire.replace(/-/g, "/"));
          let dateNow = new Date();
          let dateDiff = dateEnd.getTime() - dateNow.getTime();
          console.log(dateEnd,dateNow)
          console.log(dateDiff/(60*1000))
          if (dateDiff<30*60*1000){ //还有10分钟过期，刷新token
  
            if (!window.isReresh){
              window.isReresh = true;
              refreshToken().then(res=>{
                setToken(res.token)
                sessionSave("timeout",res.expires)
              }).catch(err=>{
                window.location.href="/redlogin/#/login"
       
              })
            }else{
              window.isReresh = false;
            }
          }
        }
        
        return data
    },
    error => {
      if (error.response.status==401){
        sessionStorage.clear()
        window.location.href="/redlogin/#/login"
        return ;
      }
      //Message.error('服务内部错误')
      // 对响应错误做点什么
      console.log(error,111111111111)
      return Promise.reject(error)
    })
}
  // 创建实例
  create () {
    let conf = {
      baseURL: baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        'X-URL-PATH': location.pathname
      }
    }
    return Axios.create(conf)
  }
  // 合并请求实例
  mergeReqest (instances = []) {
    //
  }
  // 请求实例
  request (options) {
    var instance = this.create()
    this.interceptors(instance, options.url)
    options = Object.assign({}, options)
    this.queue[options.url] = instance
    return instance(options)
  }
}
export default httpRequest
